<template>
	<view class="bookings-container">
		<!-- 顶部标题区域 -->
		<view class="header-section">
			<view class="header-card">
				<view class="header-content">
					<view class="header-title">
						<text class="title-text">我的预约</text>
						<text class="title-subtitle">My Bookings</text>
					</view>
					<view class="header-icon">📋</view>
				</view>
			</view>
		</view>

		<!-- 筛选区域 -->
		<view class="tabs-section">
			<view class="tabs-card">
				<view class="tabs-container">
					<view class="tabs-wrapper">
						<view 
							class="tab-item" 
							:class="{ active: currentFilter === 'all' }"
							@click="setFilter('all')"
						>
							<text class="tab-text" :class="{ 'tab-text-active': currentFilter === 'all' }">全部</text>
							<view class="tab-indicator" :class="{ 'tab-indicator-active': currentFilter === 'all' }"></view>
						</view>
						<view 
							class="tab-item" 
							:class="{ active: currentFilter === 'incomplete' }"
							@click="setFilter('incomplete')"
						>
							<text class="tab-text" :class="{ 'tab-text-active': currentFilter === 'incomplete' }">未完成</text>
							<view class="tab-indicator" :class="{ 'tab-indicator-active': currentFilter === 'incomplete' }"></view>
						</view>
						<view 
							class="tab-item" 
							:class="{ active: currentFilter === 'completed' }"
							@click="setFilter('completed')"
						>
							<text class="tab-text" :class="{ 'tab-text-active': currentFilter === 'completed' }">已完成</text>
							<view class="tab-indicator" :class="{ 'tab-indicator-active': currentFilter === 'completed' }"></view>
						</view>
						<view 
							class="tab-item" 
							:class="{ active: currentFilter === 'rejected' }"
							@click="setFilter('rejected')"
						>
							<text class="tab-text" :class="{ 'tab-text-active': currentFilter === 'rejected' }">已拒绝</text>
							<view class="tab-indicator" :class="{ 'tab-indicator-active': currentFilter === 'rejected' }"></view>
						</view>
						<view 
							class="tab-item" 
							:class="{ active: currentFilter === 'cancelled' }"
							@click="setFilter('cancelled')"
						>
							<text class="tab-text" :class="{ 'tab-text-active': currentFilter === 'cancelled' }">已取消</text>
							<view class="tab-indicator" :class="{ 'tab-indicator-active': currentFilter === 'cancelled' }"></view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 预约列表区域 -->
		<view class="bookings-section">
			<view class="bookings-card">
				<view class="section-header">
					<view class="section-title-wrapper">
						<text class="section-title">预约列表</text>
						<text class="section-count">({{ total }})</text>
					</view>
					<view class="date-filter-wrapper">
						<view class="date-range-picker">
							<picker 
								mode="date" 
								:value="startdate" 
								@change="onStartDateChange"
							>
								<view class="date-picker">
									<text class="date-icon">📅</text>
									<text class="date-text" :class="{ 'date-placeholder': !startdate }">
										{{ startdate || '开始日期' }}
									</text>
								</view>
							</picker>
							<text class="date-separator">至</text>
							<picker 
								mode="date" 
								:value="enddate" 
								@change="onEndDateChange"
							>
								<view class="date-picker">
									<text class="date-icon">📅</text>
									<text class="date-text" :class="{ 'date-placeholder': !enddate }">
										{{ enddate || '结束日期' }}
									</text>
								</view>
							</picker>
						</view>
						<view class="filter-actions">
							<view class="filter-btn reset-btn" @click="resetDateFilter">
								<text class="btn-text">重置</text>
							</view>
							<view class="filter-btn search-btn" @click="applyDateFilter">
								<text class="btn-text">查询</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 加载状态 -->
				<view v-if="isLoading" class="loading-state">
					<view class="loading-icon">⏳</view>
					<text class="loading-text">加载中...</text>
				</view>
				
				<!-- 空状态 -->
				<view v-else-if="filteredBookings.length === 0" class="empty-state">
					<view class="empty-icon">📅</view>
					<text class="empty-title">暂无预约</text>
					<text class="empty-desc">{{ getEmptyDesc() }}</text>
				</view>
				
				<view v-else-if="!isLoading" class="bookings-list">
					<view 
						class="booking-item" 
						v-for="(booking, index) in filteredBookings" 
						:key="index"
					>
						<view class="booking-content" @click="viewBookingDetail(booking)">
							<view class="booking-header">
								<view class="booking-title">{{ booking.meetingName }}</view>
								<view class="booking-status" :class="booking.status">
									<text class="status-text">{{ getStatusText(booking.status) }}</text>
								</view>
							</view>
							
							<view class="booking-info">
								<view class="info-row">
									<text class="info-label">会议室：</text>
									<text class="info-value">{{ booking.roomName }}</text>
								</view>
								<view class="info-row">
									<text class="info-label">日期：</text>
									<text class="info-value">{{ formatDate(booking.meetingDate) }}</text>
								</view>
								<view class="info-row">
									<text class="info-label">时间：</text>
									<text class="info-value">{{ booking.meetingTimeRange.start }} - {{ booking.meetingTimeRange.end }}</text>
								</view>
								<view class="info-row">
									<text class="info-label">召集人：</text>
									<text class="info-value">{{ booking.organizer }}</text>
								</view>
								<view class="info-row">
									<text class="info-label">预约人：</text>
									<text class="info-value">{{ booking.reserver }}</text>
								</view>
								<!-- 显示是否到分局信息 -->
								<view class="info-row" v-if="booking.need_branch_office === 'yes'">
									<text class="info-label">到分局：</text>
									<text class="info-value">{{ booking.selected_branches || '已选择分局' }}</text>
								</view>
								<!-- 已拒绝的预约显示拒绝原因 -->
								<view class="info-row" v-if="booking.state === '3' && booking.yuanyin">
									<text class="info-label">拒绝原因：</text>
									<text class="info-value reject-reason">{{ booking.yuanyin }}</text>
								</view>
							</view>
						</view>
						
						<!-- 操作按钮 -->
						<view class="booking-actions-wrapper">
							<!-- 创建时间 -->
							<view class="booking-time" v-if="booking.createdAt">
								<text class="time-text">{{ formatDateTime(booking.createdAt) }}</text>
							</view>
							<!-- 操作按钮 -->
							<view class="booking-actions" v-if="booking.state === '1' || (booking.state === '2' && (booking.status === 'pending' || booking.status === 'upcoming' || booking.status === 'ongoing')) || booking.state === '3'">
								<view class="action-btn edit-btn" @click.stop="editBooking(booking)">
									<text class="btn-text">修改</text>
								</view>
								<!-- 已拒绝的预约不显示取消按钮 -->
								<view class="action-btn cancel-btn" v-if="booking.state !== '3'" @click.stop="cancelBooking(booking)">
									<text class="btn-text">取消</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 加载更多提示 -->
				<view v-if="!isLoading && filteredBookings.length > 0" class="load-more-section">
					<view v-if="isLoadingMore" class="loading-more">
						<text class="loading-more-text">加载中...</text>
					</view>
					<view v-else-if="!hasMore" class="no-more">
						<text class="no-more-text">没有更多数据了</text>
					</view>
					<view v-else class="load-more-hint">
						<text class="load-more-hint-text">上拉加载更多</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import api, { handleApiError } from '@/utils/api.js'

export default {
	data() {
		// 获取日期范围
		const today = new Date();
		const minDate = new Date(today);
		minDate.setFullYear(today.getFullYear() - 2); // 最早2年前
		const maxDate = new Date(today);
		
		// 格式化日期辅助函数
		const formatDateForPicker = (date) => {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		};
		
		return {
			currentFilter: 'all', // 默认显示全部
			activeBookingsList: [],
			isLoading: false,
			roomMap: {}, // 会议室映射，key为pid，value为会议室名称
			userMap: {}, // 用户映射，key为userId，value为用户信息
			currentUser: null, // 当前用户信息
			isFirstLoad: true, // 标记是否首次加载，避免 mounted 和 onShow 重复调用
			startdate: '', // 开始日期
			enddate: '', // 结束日期
			minDate: formatDateForPicker(minDate), // 最早可选日期
			maxDate: formatDateForPicker(maxDate), // 最晚可选日期（今天）
			// 分页相关
			pageNum: 1, // 当前页码
			pageSize: 10, // 每页数量
			total: 0, // 总数量
			hasMore: true, // 是否还有更多数据
			isLoadingMore: false // 是否正在加载更多
		}
	},
	computed: {
		filteredBookings() {
			// 直接返回接口返回的数据，不在前端过滤
				return this.activeBookingsList;
		}
	},
	async mounted() {
		// 先加载基础数据
		await Promise.all([
			this.loadCurrentUser(),
			this.loadRoomList(),
			this.loadUserList()
		]);
		// 加载预约数据（根据当前筛选条件）
		this.resetAndLoad();
		this.isFirstLoad = false; // 标记首次加载完成
	},
	onShow() {
		// 页面显示时刷新数据（避免与 mounted 重复调用）
		// 只在非首次加载时刷新
		if (!this.isFirstLoad) {
			// 确保用户信息已加载
			if (this.currentUser && this.currentUser.userId) {
				this.resetAndLoad();
			} else {
				// 如果用户信息不存在，先加载用户信息
				this.loadCurrentUser().then(() => {
					if (this.currentUser && this.currentUser.userId) {
						this.resetAndLoad();
					}
				});
			}
		}
	},
	onReachBottom() {
		// 上拉加载更多
		if (this.hasMore && !this.isLoadingMore && !this.isLoading) {
			this.loadMore();
		}
	},
	methods: {
		// 格式化时间，只显示时分
		formatTime(time) {
			if (!time) return '09:00';
			// 如果包含秒，去掉秒
			if (time.includes(':') && time.split(':').length === 3) {
				return time.substring(0, 5);
			}
			return time;
		},
		
		// 加载当前用户信息
		async loadCurrentUser() {
			try {
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo && storedUserInfo.userId) {
					this.currentUser = {
						userId: storedUserInfo.userId,
						userName: storedUserInfo.userName || storedUserInfo.username,
						nickName: storedUserInfo.nickName || storedUserInfo.nickname
					};
				}
				
				// 从接口获取最新用户信息
				const response = await api.getUserInfo();
				if (response && response.code === 200 && response.user) {
					const user = response.user;
					if (!user.userId) {
						console.error('用户信息中缺少userId');
						return;
					}
					this.currentUser = {
						userId: user.userId,
						userName: user.userName,
						nickName: user.nickName
					};
				} else {
					console.error('获取用户信息失败:', response?.msg);
				}
			} catch (error) {
				console.error('获取当前用户信息错误:', error);
				// 如果获取失败，尝试使用本地存储的信息
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo && storedUserInfo.userId) {
					this.currentUser = {
						userId: storedUserInfo.userId,
						userName: storedUserInfo.userName || storedUserInfo.username,
						nickName: storedUserInfo.nickName || storedUserInfo.nickname
					};
				}
			}
		},
		
		// 加载会议室列表
		async loadRoomList() {
			try {
				const response = await api.getRoomList();
				if (response && response.code === 200) {
					const rooms = response.rows || [];
					this.roomMap = {};
					rooms.forEach(room => {
						const roomId = room.roomId || room.id;
						const roomName = room.roomName || room.name || '未知会议室';
						this.roomMap[roomId] = roomName;
					});
				}
			} catch (error) {
				console.error('获取会议室列表错误:', error);
			}
		},
		
		// 加载用户列表
		async loadUserList() {
			try {
				const response = await api.getUserList();
				if (response && response.code === 200) {
					const users = response.rows || [];
					this.userMap = {};
					users.forEach(user => {
						const userId = user.userId;
						this.userMap[userId] = {
							nickName: user.nickName || user.userName,
							userName: user.userName
						};
					});
				}
			} catch (error) {
				console.error('获取用户列表错误:', error);
			}
		},
		
		// 重置并加载数据（用于筛选条件改变时）
		resetAndLoad() {
			this.pageNum = 1;
			this.hasMore = true;
			this.activeBookingsList = [];
			this.loadBookings();
		},
		
		// 加载更多数据
		async loadMore() {
			if (!this.hasMore || this.isLoadingMore || this.isLoading) {
				return;
			}
			
			this.isLoadingMore = true;
			this.pageNum += 1;
			await this.loadBookings(true);
		},
		
		// 加载预约数据（整合了历史记录功能）
		async loadBookings(isLoadMore = false) {
			if (!this.currentUser || !this.currentUser.userId) {
				console.warn('未获取到当前用户信息');
				uni.showToast({
					title: '获取用户信息失败，请重新登录',
					icon: 'none',
					duration: 2000
				});
				// 尝试重新加载用户信息
				await this.loadCurrentUser();
				if (!this.currentUser || !this.currentUser.userId) {
					this.activeBookingsList = [];
					this.isLoading = false;
					this.isLoadingMore = false;
					return;
				}
			}
			
			if (!isLoadMore) {
				this.isLoading = true;
			}
			
			try {
				// 确保 reservedby 必传，使用当前用户的 ID
				const currentUserId = this.currentUser.userId;
				if (!currentUserId) {
					throw new Error('当前用户ID不能为空');
				}
				
				// 根据筛选条件构建请求参数
				const params = {
					reservedby: currentUserId,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					orderByColumn: 'id',
					isAsc: 'desc'
				};
				
				// 如果选择了日期区间，添加startdate和enddate参数
				if (this.startdate) {
					params.startdate = this.startdate;
				}
				if (this.enddate) {
					params.enddate = this.enddate;
				}
				
				// 根据筛选条件传state参数
				// 全部：不传state，显示所有状态
				// 未完成：不传state，前端过滤待审核和未完成的已通过
				// 已完成：传state=2，前端再过滤时间已过的
				// 审核拒绝：传state=3
				// 已取消：传state=4
				if (this.currentFilter === 'completed') {
					params.state = '2'; // 已完成（已通过）
				} else if (this.currentFilter === 'rejected') {
					params.state = '3'; // 拒绝
				} else if (this.currentFilter === 'cancelled') {
					params.state = '4'; // 已取消
				}
				// 全部和未完成不传state参数，后续会过滤
				
				// 查询当前用户的预约（根据 reservedby 字段和 state 参数）
				// 不传递 startDate 和 endDate 参数
				const response = await api.getMeetingsByMonth(null, null, params);
				
				if (response && response.code === 200) {
					const meetings = response.rows || [];
					this.total = response.total || 0;
					
					// 转换数据格式
					const newBookings = meetings
						.map(meeting => {
							// 根据state和时间判断状态（用于显示）
							let status = 'pending';
							if (meeting.state === '1') {
								status = 'pending'; // 待审核
							} else if (meeting.state === '2') {
								// 已通过，根据时间判断
								if (this.isMeetingCompleted(meeting)) {
									status = 'completed'; // 已完成
								} else {
									status = this.getMeetingStatusByTime(meeting); // 未完成（即将开始、进行中）
								}
							} else if (meeting.state === '3') {
								status = 'rejected'; // 审核拒绝
							} else if (meeting.state === '4') {
								status = 'cancelled'; // 已取消
							}
							
							return {
								id: meeting.id,
								meetingName: meeting.meetingtitle || '会议',
								roomName: this.roomMap[meeting.pid] || '未知会议室',
								roomId: meeting.pid, // 添加会议室ID，用于编辑
								meetingDate: meeting.thedate,
								meetingTimeRange: {
									start: this.formatTime(meeting.startTime),
									end: this.formatTime(meeting.endTime)
								},
								organizer: this.userMap[meeting.convener]?.nickName || '未知',
								organizerId: meeting.convener, // 添加召集人ID，用于编辑
								reserver: this.userMap[meeting.reservedby]?.nickName || '未知',
								reserverId: meeting.reservedby, // 添加预约人ID
								participants: meeting.content || '',
								status: status,
								meetingSupport: meeting.ensure === 1 ? 'yes' : 'no',
								need_branch_office: meeting.need_branch_office === 1 ? 'yes' : 'no',
								selected_branches: meeting.selected_branches || '',
								remark: meeting.remark || '',
								state: meeting.state,
								yuanyin: meeting.yuanyin || '',
								createdAt: meeting.createTime || '' // 添加创建时间，用于历史记录排序
							};
						})
						.filter(booking => {
							// 根据筛选条件进一步过滤
							if (this.currentFilter === 'all') {
								return true; // 全部：显示所有状态
							} else if (this.currentFilter === 'incomplete') {
								// 未完成：待审核(state=1) + 已通过但未完成的(state=2且时间未过)
								return booking.state === '1' || (booking.state === '2' && booking.status !== 'completed');
							} else if (this.currentFilter === 'completed') {
								// 已完成：state=2且时间已过
								return booking.status === 'completed';
							} else if (this.currentFilter === 'rejected') {
								// 审核拒绝：state=3
								return booking.status === 'rejected';
							} else if (this.currentFilter === 'cancelled') {
								// 已取消：state=4
								return booking.status === 'cancelled';
							}
							return true;
						});
					
					// 如果是加载更多，追加到列表；否则替换列表
					if (isLoadMore) {
						this.activeBookingsList = [...this.activeBookingsList, ...newBookings];
					} else {
						this.activeBookingsList = newBookings;
					}
					
					// 判断是否还有更多数据
					this.hasMore = this.activeBookingsList.length < this.total;
				} else {
					console.error('获取预约列表失败:', response?.msg);
					if (!isLoadMore) {
						this.activeBookingsList = [];
					}
					this.hasMore = false;
				}
			} catch (error) {
				console.error('获取预约列表错误:', error);
				handleApiError(error);
				if (!isLoadMore) {
					this.activeBookingsList = [];
				}
				this.hasMore = false;
			} finally {
				this.isLoading = false;
				this.isLoadingMore = false;
			}
		},
		
		// 根据时间判断会议状态
		getMeetingStatusByTime(meeting) {
			const now = new Date();
			const meetingDate = new Date(meeting.thedate);
			const startTime = meeting.startTime;
			const endTime = meeting.endTime;
			
			if (startTime && endTime) {
				const [startHour, startMin] = startTime.split(':').map(Number);
				const [endHour, endMin] = endTime.split(':').map(Number);
				const startDateTime = new Date(meetingDate);
				startDateTime.setHours(startHour, startMin, 0, 0);
				const endDateTime = new Date(meetingDate);
				endDateTime.setHours(endHour, endMin, 0, 0);
				
				if (now < startDateTime) {
					return 'upcoming'; // 即将开始
				} else if (now >= startDateTime && now <= endDateTime) {
					return 'ongoing'; // 进行中
				} else {
					return 'completed'; // 已完成（这个状态不应该出现在我的预约页面）
				}
			}
			
			return 'upcoming';
		},
		
		// 判断会议是否已完成（时间已过）
		isMeetingCompleted(meeting) {
			const now = new Date();
			const meetingDate = new Date(meeting.thedate);
			const endTime = meeting.endTime;
			
			if (endTime) {
				const [endHour, endMin] = endTime.split(':').map(Number);
				const endDateTime = new Date(meetingDate);
				endDateTime.setHours(endHour, endMin, 0, 0);
				
				// 如果结束时间已过，则认为已完成
				return now > endDateTime;
			}
			
			return false;
		},
		
		// 格式化日期用于API请求
		formatDateForApi(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		
		setFilter(filter) {
			// 切换筛选条件时，重新调用接口加载数据
			if (this.currentFilter !== filter) {
				this.currentFilter = filter;
				this.resetAndLoad();
			}
		},
		
		// 开始日期改变
		onStartDateChange(e) {
			if (e && e.detail && e.detail.value) {
				const newStartDate = e.detail.value;
				// 如果开始日期大于结束日期，清空结束日期
				if (this.enddate && newStartDate > this.enddate) {
					this.enddate = '';
				}
				this.startdate = newStartDate;
			}
		},
		
		// 结束日期改变
		onEndDateChange(e) {
			// 确保事件对象和值存在
			if (!e || !e.detail) {
				return;
			}
			
			const selectedEndDate = e.detail.value;
			
			// 如果没有选择值（用户取消），不处理
			if (!selectedEndDate) {
				return;
			}
			
			// 验证：如果结束日期和开始日期相同，这是允许的
			// 如果结束日期小于开始日期，提示用户并阻止设置
			if (this.startdate) {
				// 使用 Date 对象进行更可靠的日期比较
				const startDateObj = new Date(this.startdate);
				const endDateObj = new Date(selectedEndDate);
				
				if (endDateObj < startDateObj) {
					uni.showToast({
						title: '结束日期不能早于开始日期',
						icon: 'none',
						duration: 2000
					});
					// 不更新 enddate，保持原值
					return;
				}
			}
			
			// 正常设置结束日期
			this.enddate = selectedEndDate;
		},
		
		// 重置日期筛选
		resetDateFilter() {
			this.startdate = '';
			this.enddate = '';
			// 重新加载数据
			setTimeout(() => {
				this.resetAndLoad();
			}, 100);
		},
		
		// 应用日期筛选
		applyDateFilter() {
			// 重新加载数据
			setTimeout(() => {
				this.resetAndLoad();
			}, 100);
		},
		getStatusText(status) {
			// 在未完成筛选下，统一显示为"待开始"和"进行中"
			if (this.currentFilter === 'incomplete') {
				const incompleteStatusMap = {
					'pending': '待开始',
					'upcoming': '待开始',
					'ongoing': '进行中',
					'completed': '已完成',
					'rejected': '已拒绝',
					'cancelled': '已取消'
				};
				return incompleteStatusMap[status] || status;
			}
			
			// 其他筛选下的状态显示
			const statusMap = {
				'pending': '待审核',
				'upcoming': '即将开始',
				'ongoing': '进行中',
				'completed': '已完成',
				'rejected': '已拒绝',
				'cancelled': '已取消'
			};
			return statusMap[status] || status;
		},
		getEmptyDesc() {
			const descMap = {
				'all': '您还没有预约记录',
				'incomplete': '您还没有未完成的预约',
				'completed': '您还没有已完成的预约',
				'rejected': '您还没有被拒绝的预约',
				'cancelled': '您还没有已取消的预约'
			};
			return descMap[this.currentFilter] || '暂无预约';
		},
		formatDate(dateStr) {
			if (!dateStr) return '';
			const dateParts = dateStr.split('-');
			if (dateParts.length === 3) {
				const year = dateParts[0];
				const month = parseInt(dateParts[1]);
				const day = parseInt(dateParts[2]);
				return `${year}年${month}月${day}日`;
			}
			return dateStr;
		},
		formatDateTime(dateTimeStr) {
			if (!dateTimeStr) return '';
			
			let date;
			
			// iOS兼容性：尝试多种日期解析方式
			// 方式1：直接使用 Date 构造函数
			date = new Date(dateTimeStr);
			
			// 检查日期是否有效
			if (isNaN(date.getTime())) {
				// 方式2：如果是时间戳（字符串格式）
				if (/^\d+$/.test(dateTimeStr)) {
					const timestamp = parseInt(dateTimeStr);
					// 判断是秒还是毫秒（通常13位是毫秒，10位是秒）
					date = new Date(timestamp < 10000000000 ? timestamp * 1000 : timestamp);
				} else {
					// 方式3：手动解析常见格式
					// 处理格式如：2024-01-01 12:00:00 或 2024-01-01T12:00:00
					const dateStr = String(dateTimeStr).trim();
					// 移除可能的时区信息
					const cleanStr = dateStr.replace(/[TZ]/g, ' ').replace(/\.\d{3}/g, '').trim();
					
					// 尝试解析 YYYY-MM-DD HH:mm:ss 格式
					const match = cleanStr.match(/(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2})(?::(\d{2}))?)?/);
					if (match) {
						const [, year, month, day, hour = '0', minute = '0', second = '0'] = match;
						date = new Date(
							parseInt(year),
							parseInt(month) - 1,
							parseInt(day),
							parseInt(hour),
							parseInt(minute),
							parseInt(second)
						);
					} else {
						// 如果都解析失败，返回原始字符串或空
						console.warn('无法解析日期格式:', dateTimeStr);
						return dateTimeStr;
					}
				}
			}
			
			// 再次检查日期是否有效
			if (isNaN(date.getTime())) {
				console.warn('日期解析失败:', dateTimeStr);
				return dateTimeStr;
			}
			
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}`;
		},
		viewBookingDetail(booking) {
			let content = `会议名称：${booking.meetingName}\n会议室：${booking.roomName}\n日期：${this.formatDate(booking.meetingDate)}\n时间：${booking.meetingTimeRange.start} - ${booking.meetingTimeRange.end}\n召集人：${booking.organizer}`;
			
			if (booking.reserver) {
				content += `\n预约人：${booking.reserver}`;
			}
			
			if (booking.participants) {
				content += `\n参会人员：${booking.participants}`;
			}
			
			content += `\n会议保障：${booking.meetingSupport === 'yes' ? '需要' : '不需要'}`;
			
			// 显示是否到分局信息
			if (booking.need_branch_office === 'yes') {
				content += `\n是否到分局：是`;
				if (booking.selected_branches) {
					content += `\n选择的分局：${booking.selected_branches}`;
				}
			} else {
				content += `\n是否到分局：否`;
			}
			
			if (booking.remark) {
				content += `\n备注：${booking.remark}`;
			}
			
			if (booking.createdAt) {
				content += `\n创建时间：${this.formatDateTime(booking.createdAt)}`;
			}
			
			if (booking.state === '3' && booking.yuanyin) {
				content += `\n拒绝原因：${booking.yuanyin}`;
			}
			
			if (booking.state === '4') {
				content += `\n（该预约已取消）`;
			}
			
			uni.showModal({
				title: '预约详情',
				content: content,
				showCancel: false,
				confirmText: '确定'
			});
		},
		
		// 编辑预约
		async editBooking(booking) {
			// 允许修改：待审核、未开始的已通过预约、已拒绝的预约
			const canEdit = booking.state === '1' || 
			               (booking.state === '2' && (booking.status === 'pending' || booking.status === 'upcoming' || booking.status === 'ongoing')) ||
			               booking.state === '3';
			
			if (!canEdit) {
				uni.showToast({
					title: '当前状态的预约不能修改',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			// 将预约数据存储到本地，然后跳转到编辑页面
			const bookingData = {
				id: booking.id,
				meetingtitle: booking.meetingName,
				pid: booking.roomId,
				convener: booking.organizerId,
				thedate: booking.meetingDate,
				startTime: booking.meetingTimeRange.start,
				endTime: booking.meetingTimeRange.end,
				content: booking.participants,
				ensure: booking.meetingSupport === 'yes' ? 1 : 0,
				remark: booking.remark || '',
				state: booking.state,
				yuanyin: booking.yuanyin || '' // 已拒绝的预约回显拒绝原因
			};
			
			// 存储到本地，供编辑页面使用
			uni.setStorageSync('editBookingData', bookingData);
			
			// 跳转到预约页面，传递预约ID和会议室ID
			uni.navigateTo({
				url: `/pages/enroll/predetermined?editId=${booking.id}&roomId=${booking.roomId}`
			});
		},
		
		// 取消预约（待审批或未开始的已通过预约）
		async cancelBooking(booking) {
			if (booking.state !== '1' && !(booking.state === '2' && booking.status === 'upcoming')) {
				uni.showToast({
					title: '当前状态不可取消',
					icon: 'none'
				});
				return;
			}
			
			uni.showModal({
				title: '确认取消',
				content: '确定要取消此预约吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 使用编辑接口，将状态置为4（取消）
							const resp = await api.updateYuyue({ id: booking.id, state: '4' });
							if (resp && resp.code === 200) {
								uni.showToast({ title: '已取消', icon: 'success' });
								// 重新加载列表
								this.resetAndLoad();
							} else {
								uni.showToast({ title: resp?.msg || '取消失败', icon: 'none' });
							}
						} catch (error) {
							handleApiError(error);
						}
					}
				}
			});
		}
	}
}
</script>

<style lang="less" scoped>
page {
	background-color: #f5f5f5;
}

.bookings-container {
	padding: 30rpx;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	min-height: 100vh;
}

/* 顶部标题区域 */
.header-section {
	margin-bottom: 30rpx;
}

.header-card {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.header-title {
	flex: 1;
}

.title-text {
	font-size: 48rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.title-subtitle {
	font-size: 24rpx;
	color: #666;
	opacity: 0.8;
}

.header-icon {
	font-size: 60rpx;
	margin-left: 20rpx;
}

/* 筛选区域 */
.tabs-section {
	margin-bottom: 30rpx;
}

.tabs-card {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 20rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.tabs-container {
	width: 100%;
	background: rgba(248, 249, 250, 0.8);
	border-radius: 12rpx;
	padding: 4rpx;
	overflow: hidden;
}

.tabs-wrapper {
	display: flex;
	width: 100%;
	background: transparent;
	padding: 0;
	position: relative;
	justify-content: space-around;
}

.tab-item {
	// flex: 1;
	text-align: center;
	padding: 20rpx 6rpx;
	border-radius: 8rpx;
	background: transparent;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	min-width: 0;
}

.tab-item:active {
	transform: scale(0.95);
	transition: transform 0.1s ease;
}

.tab-item.active {
	background: rgba(255, 255, 255, 0);
}

.tab-text {
	font-size: 28rpx;
	font-weight: 500;
	color: #666;
	display: block;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	position: relative;
	z-index: 2;
}

.tab-text-active {
	color: #2870E5;
	font-weight: 600;
	font-size: 30rpx;
	transform: scale(1.05);
}

.tab-indicator {
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%) scaleX(0);
	width: 60%;
	height: 4rpx;
	background: linear-gradient(90deg, #2870E5 0%, #4A90E2 100%);
	border-radius: 2rpx;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	opacity: 0;
}

.tab-indicator-active {
	transform: translateX(-50%) scaleX(1);
	opacity: 1;
	box-shadow: 0 2rpx 8rpx rgba(40, 112, 229, 0.3);
}

/* 预约列表区域 */
.bookings-section {
	margin-bottom: 30rpx;
}

.bookings-card {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.section-header {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.section-title-wrapper {
	display: flex;
	align-items: center;
	gap: 8rpx;
	flex-shrink: 0;
}

.section-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.section-count {
	font-size: 28rpx;
	color: #666;
}

/* 日期筛选区域 - 移到section-header内 */
.date-filter-wrapper {
	display: flex;
	align-items: center;
	gap: 12rpx;
	width: 100%;
	justify-content: flex-start;
	flex-wrap: wrap;
}

.date-range-picker {
	display: flex;
	align-items: center;
	gap: 8rpx;
	flex: 1;
	flex-wrap: wrap;
}

.date-separator {
	font-size: 24rpx;
	color: #606266;
	flex-shrink: 0;
	padding: 0 4rpx;
}

.date-picker {
	display: flex;
	align-items: center;
	// padding: 10rpx 14rpx;
	background: rgba(248, 249, 250, 0.8);
	border-radius: 8rpx;
	border: 2rpx solid transparent;
	transition: all 0.3s ease;
	gap: 8rpx;
	min-width: 140rpx;
	flex: 1;
	flex-shrink: 0;
}

.date-picker:active {
	background: rgba(248, 249, 250, 1);
	border-color: #2870E5;
}

.date-icon {
	font-size: 24rpx;
	flex-shrink: 0;
}

.date-text {
	font-size: 24rpx;
	color: #333;
	flex: 1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.date-text.date-placeholder {
	color: #999;
}

.filter-actions {
	display: flex;
	gap: 8rpx;
	flex-shrink: 0;
}

.filter-btn {
	padding: 10rpx 16rpx;
	border-radius: 6rpx;
	font-size: 22rpx;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.3s ease;
	white-space: nowrap;
}

.reset-btn {
	background: rgba(248, 249, 250, 0.8);
	color: #666;
}

.reset-btn:active {
	background: rgba(248, 249, 250, 1);
	transform: scale(0.95);
}

.search-btn {
	background: linear-gradient(135deg, #2870E5 0%, #4A90E2 100%);
	color: #fff;
	box-shadow: 0 4rpx 12rpx rgba(40, 112, 229, 0.3);
}

.search-btn:active {
	transform: scale(0.95);
	box-shadow: 0 2rpx 8rpx rgba(40, 112, 229, 0.3);
}

.btn-text {
	font-size: 22rpx;
}

/* 空状态 */
.empty-state {
	text-align: center;
	padding: 80rpx 0;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 20rpx;
	opacity: 0.5;
}

.empty-title {
	font-size: 32rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.empty-desc {
	font-size: 26rpx;
	color: #999;
}

/* 预约列表 */
.bookings-list {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
}

.booking-item {
	background: rgba(255, 255, 255, 0.8);
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	padding: 30rpx;
	transition: all 0.3s ease;
	display: flex;
	flex-direction: column;
}

.booking-content {
	flex: 1;
	cursor: pointer;
}

.booking-item:active .booking-content {
	transform: scale(0.98);
}

.booking-actions-wrapper {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 2rpx solid #f0f0f0;
}

.booking-time {
	flex: 1;
}

.time-text {
	font-size: 24rpx;
	color: #999;
}

.booking-actions {
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
}

.action-btn {
	padding: 12rpx 30rpx;
	border-radius: 8rpx;
	font-size: 26rpx;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.3s ease;
	text-align: center;
}

.edit-btn {
	background: #2870E5;
	color: #fff;
}

.edit-btn:active {
	background: #1e5bb8;
	transform: scale(0.95);
}

.cancel-btn {
	background: #ff4d4f;
	color: #fff;
}

.cancel-btn:active {
	background: #d9363e;
	transform: scale(0.95);
}

.btn-text {
	font-size: 26rpx;
}

.booking-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.booking-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
}

.booking-status {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: 600;
}

.booking-status.pending {
	background: rgba(250, 173, 20, 0.1);
	color: #faad14;
}

.booking-status.upcoming {
	background: rgba(40, 112, 229, 0.1);
	color: #2870E5;
}

.booking-status.ongoing {
	background: rgba(250, 140, 22, 0.1);
	color: #fa8c16;
}

.booking-status.completed {
	background: rgba(82, 196, 26, 0.1);
	color: #52c41a;
}

.booking-status.rejected {
	background: rgba(255, 77, 79, 0.1);
	color: #ff4d4f;
}

.booking-status.cancelled {
	background: rgba(153, 153, 153, 0.1);
	color: #999;
}

.status-text {
	font-size: 24rpx;
}

.booking-info {
	margin-bottom: 25rpx;
}

.info-row {
	display: flex;
	margin-bottom: 12rpx;
}

.info-row:last-child {
	margin-bottom: 0;
}

.info-label {
	font-size: 26rpx;
	color: #666;
	width: 130rpx;
	flex-shrink: 0;
}

.info-value {
	font-size: 26rpx;
	color: #333;
	flex: 1;
}

.reject-reason {
	color: #ff4d4f;
	font-weight: 500;
}

/* 加载状态 */
.loading-state {
	text-align: center;
	padding: 80rpx 0;
}

.loading-icon {
	font-size: 60rpx;
	margin-bottom: 20rpx;
	animation: spin 1s linear infinite;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* 加载更多区域 */
.load-more-section {
	padding: 40rpx 0;
	text-align: center;
}

.loading-more {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 12rpx;
}

.loading-more-text {
	font-size: 26rpx;
	color: #666;
}

.no-more {
	padding: 20rpx 0;
}

.no-more-text {
	font-size: 24rpx;
	color: #999;
}

.load-more-hint {
	padding: 20rpx 0;
}

.load-more-hint-text {
	font-size: 24rpx;
	color: #999;
}

</style>

